package com.bookstore.servlet;

import com.bookstore.entity.Product;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

@WebServlet("/client/cart.do")
public class CartServlet extends BaseServlet {
    protected void insert(HttpServletRequest request, HttpServletResponse response) {
        //参数获取
        Long productId = Long.valueOf(request.getParameter("productId"));
        String productName = request.getParameter("productName");
        Double price = Double.valueOf(request.getParameter("price"));
        String category = request.getParameter("category");
        String description = request.getParameter("description");
        //将参数封装成商品对象
        Product product = new Product(productId, productName, price, category, description);
        HttpSession session = request.getSession();
        //将 Product 作为 Key (根据 productId 作为 equals 和 hashCode 的条件)， 商品数量作为 Value
        HashMap<Product, Integer> productMap = (HashMap<Product, Integer>) session.getAttribute("productMap");
        //如果在Session中没有保存过该Map，就新建一个
        if (productMap == null) {
            productMap = new HashMap<Product, Integer>();
        }
        //获取商品数量
        Integer pNum = productMap.get(product);
        if (pNum == null) {
            productMap.put(product, 1);
        } else {
            productMap.put(product, pNum + 1);
        }
        session.setAttribute("productMap", productMap);
        System.out.println(productMap);
    }

    protected void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //参数获取
        Long productId = Long.valueOf(request.getParameter("productId"));
        Product product = new Product();
        product.setId(productId);
        HttpSession session = request.getSession();
        HashMap<Product, Integer> productMap = (HashMap<Product, Integer>) session.getAttribute("productMap");
        String message = null;
        if (productMap == null) {
            message = "删除失败";
            return;
        }
        Integer pNum = productMap.get(product);
        if (pNum == null || pNum <= 0){
            message = "删除失败";
            return;
        }
        productMap.remove(product);
        message = "删除成功";
        System.out.println(message);
        response.sendRedirect("./product_cart.jsp");
    }
}
